<template>
  <el-autocomplete
    v-model="select"
    v-bind="$attrs"
    placeholder="请输入客户名称"
    popper-class="customer-autocomplete"
    value-key="customer_name"
    :fetch-suggestions="throttleGetData"
    @input="changeValue"
    @select="handleSelectFarm"
  >
    <template slot-scope="props">
      <div class="farm-name">{{ props.item.customer_name || '' }}</div>
      <small class="text-muted">
        {{ props.item.address || '' }}
      </small>
    </template>
  </el-autocomplete>
</template>

<script>
import { throttle } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
export default {
  components: {},
  props: {
    value: {
      type: String,
      default: '',
    },
  },
  model: {
    prop: 'value',
    event: 'setValue',
  },
  data() {
    return {
      select: '',
      customerParams: {
        index: 1,
        size: 10,
        'submit_person.eq': '',
        customer_name: '',
      },
      dataList: [],
    }
  },
  computed: {
    ...mapGetters(['userId']),
  },
  watch: {
    value: {
      handler: function () {
        this.select = this.value
      },
      immediate: true,
    },
  },
  created() {
    this.customerParams['submit_person.eq'] = this.userId
  },
  mounted() {},
  methods: {
    async getCustomer(queryString = '', cb) {
      queryString = queryString.trim()
      let data = []

      if (this.customerParams.customer_name === queryString) {
        cb(this.dataList)
        return
      }

      this.customerParams.customer_name = queryString
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'datum_one_county_industry', this.customerParams)
      )

      if (res && res.data) {
        data = res.data.data || []
      }

      this.dataList = [...data]

      cb(data)
    },
    throttleGetData: throttle(500, function (queryString, cb) {
      this.getCustomer(queryString, cb)
    }),
    changeValue(val) {
      this.$emit('setValue', val)
      this.$emit('change', val)
    },
    handleSelectFarm(data) {
      this.$emit('select', data)
    },
  },
}
</script>

<style lang="scss" scoped></style>
